package net.flintx.array;

public class SearchInsertPosition {

    public int searchInsert(int[] nums, int target) {
        /**
         * searchInsert
         *
         * @Description:
         *  Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
         *  You may assume no duplicates in the array.
         * @Example:
         *  Input: [1,3,5,6], 5
         *  Output: 2
         * @Params: [nums, target]
         * @Return: int
         * @Date: 2018/1/4
         */

        int left = 0, right = nums.length - 1;
        if (target > nums[right]) {
            return nums.length;
        }
        int mid = (left + right) >> 1;
        while (left < right) {
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] > target) {
                right = mid;
            } else {
                left = mid + 1;
            }
            mid = (left + right) >> 1;
        }
        return mid;
    }

    public static void main(String[] args) {
        int[] nums = {1, 3, 5, 6};
        int target = 7;
        System.out.println(new SearchInsertPosition().searchInsert(nums, target));
    }
}
